<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <el-button size="default" :icon="Paperclip" round>选择文件</el-button>
      <ellipsis :row="1" :content="placeholder + sizeTip" hoverTip class="el-upload__tip"/>
    </div>
    <div v-else-if="mode === 'PC' && !readonly" v-loading="loading">
        <el-upload :file-list="fileList" :action="uploadUrl" :limit="maxNumber" with-credentials :multiple="maxNumber > 1"
                 :headers="headers" :on-success="uploadSuccess" auto-upload :before-upload="beforeUpload"
                 :on-remove="handleRemove" :on-error="uploadFail" :accept="String(fileTypes)" :on-exceed="overLimit">
        <el-button size="default" :icon="Paperclip" round>选择文件</el-button>
        <template #tip>
          <ellipsis :row="1" :content="placeholder + sizeTip" hoverTip class="el-upload__tip"/>
        </template>
      </el-upload>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly">
      <uploader v-model="fileList" :accept="String(fileTypes)" :multiple="maxNumber > 1" :max-count="maxNumber > 0 ? maxNumber : 99"
          deletable :before-delete="handleRemove" upload-text="选择文件" :after-read="afterRead" :max-size="maxSize * 1024 * 1024"
          @oversize="onOversize" upload-icon="description">
      </uploader>
      <div style="color: #9b9595">{{ placeholder }} {{ sizeTip }}</div>
    </div>
    <div v-else class="file-preview">
      <div v-if="mode === 'PC'" class="file-preview-pc">
        <div v-for="file in _value" :key="file.id">
          <ellipsis class="file-item" type="primary" @click="download(file)" :content="file.name">
            <template #pre>
              <el-icon><Document /></el-icon>
            </template>
            <template #aft>
              <el-tag size="small">{{ getSize(file.size) }}</el-tag>
            </template>
          </ellipsis>
        </div>
      </div>
      <div v-else>
        <el-row v-for="file in _value" :key="file.id">
          <el-col :span="20">
            <ellipsis style="display: inline-block" class="file-item" type="primary" @click="download(file)" :content="file.name">
              <template #pre>
                <el-icon><Document /></el-icon>
              </template>
            </ellipsis>
          </el-col>
          <el-col :span="4">
            <el-tag size="small">{{ getSize(file.size) }}</el-tag>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import componentMinxins from '/@/views/setting/workflow/components/ComponentMinxins'
import {Uploader, showSuccessToast, showFailToast, showLoadingToast} from 'vant'
import { Paperclip, Document } from '@element-plus/icons-vue'
import { computed, reactive, toRefs } from 'vue'
import { getRes } from '/@/utils/utils'
import { ElMessage } from 'element-plus'
import request from '/@/utils/request'
import { Session } from '/@/utils/storage'

export default {
    name: 'FileUpload',
    mixins: [componentMinxins],
    components: {Uploader, Document, Paperclip},
    props: {
        placeholder: {
            type: String,
            default: '请选择附件',
        },
        modelValue: {
            type: Array,
            default: () => {
                return []
            },
        },
        maxSize: {
            type: Number,
            default: 5,
        },
        maxNumber: {
            type: Number,
            default: 10,
        },
        fileTypes: {
            type: Array,
            default: () => {
                return []
            },
        },
    },
    emits: ['update:modelValue'],
    setup(props, context) {
        const { maxSize, fileTypes, mode, maxNumber, modelValue } = toRefs(props)
        const state = reactive({
            loading: false,
            disabled: false,
            uploadUrl: `/api/file/filaAttach/upload`,
            headers: { 
              '17work': Session.get('token')
            },
        })
        const _value = computed({
            get: () => {
                return modelValue.value
            },
            set: val => {
                context.emit('update:modelValue', val)
            }
        })
        const sizeTip = computed(() => {
            if (fileTypes.value.length > 0) {
                return ` | 只允许上传[${String(fileTypes.value).replaceAll(
                    ',',
                    '、'
                )}]格式的文件，且单个附件不超过${maxSize.value}MB`
            }
            return maxSize.value > 0 ? ` | 单个附件不超过${maxSize.value}MB` : ''
        })
        const fileList = computed({
            get: () => {
                return _value.value.map((f) => {
                    return {
                        name: f.name,
                        url: f.src,
                        status: 'success',
                        file: new File([], f.name, {}),
                    }
                })
            },
            set: (val) => {}
        })
        const beforeUpload = (file) => {
            if (Array.isArray(file)) {
                for (let i = 0; i < file.length; i++) {
                    if (!validFile(file[i])) {
                        return false
                    }
                }
                return true
            } else {
                return validFile(file)
            }
        }
        const validFile = (file) => {
            if (maxSize.value > 0 && file.size / 1024 / 1024 > maxSize.value) {
                ElMessage.warning(`单个文件最大不超过 ${maxSize.value}MB`)
            } else {
                state.loading = true
                return true
            }
            return false
        }
        const getSize = (size) => {
            if (size > 1048576) {
                return (size / 1048576).toFixed(1) + 'MB'
            } else if (size > 1024) {
                return (size / 1024).toFixed(1) + 'KB'
            } else {
                return size + 'B'
            }
        }
        const removeFile = (fileId) => {
            // TO DO 这里调接口
            return
            ElMessage.success('移除文件成功')
        }
        const uploadSuccess = (response, file, fileList) => {
            state.loading = false
            console.log(response)
            _value.value.push(response.data)
            context.emit('update:modelValue', _value.value)
            ElMessage.success(response.data.name + '上传成功')
        }
        const uploadFail = (err) => {
            console.log(err)
            state.loading = false
            ElMessage.error('文件上传失败 ' + err)
        }
        const overLimit = () => {
            if (mode.value === 'PC') {
                ElMessage.warning('最多只能上传' + maxNumber.value + '个附件')
                state.loading = false
            } else {
                showFailToast('数量超出限制')
            }
        }
        const afterRead = (file) => {
            if (Array.isArray(file)) {
                file.forEach((fl) => {
                    uploadFile(fl)
                })
            } else {
                uploadFile(file)
            }
        }
        const uploadFile = (file) => {
            //上传文件
            const formData = new FormData()
            formData.append('file', file.file)
            formData.append('isImg', false)
            showLoadingToast({message: '上传中...', forbidClick: true})
            request({
                url: state.uploadUrl,
                method: 'post',
                data: formData,
                headers: {
                'Content-type': 'multipart/form-data',
                '17work': Session.get('token')
                }
            }).then(
                (res) => {
                if (res.code === 0) {
                    _value.value.push(res.data)
                    context.emit('update:modelValue', _value.value)
                    showSuccessToast('上传成功')
                }
                },
                (err) => {
                    showFailToast('上传失败')
                    console.log(err)
                }
            )
        }
        const onOversize = (file) => {
            showFailToast('文件过大')
        }
        const handleRemove = (file, fileList) => {
          let i = _value.value.findIndex((v) => v.name === file.name)
          if (i > -1) {
            //removeFile(_value.value[i].id)
            _value.value.splice(i, 1)
            context.emit('update:modelValue', _value.value)
          }
          console.log('删除文件', file)
        }
        const handlePictureCardPreview = (file) => {
          console.log(file)
        }
        const handleDownload = (file) => {
          console.log(file)
        }
        const download = (file) => {
            window.open(`${getRes(file.url)}?name=${file.name}`, '_blank')
        }
        return {
            ...toRefs(state),
            Paperclip,
            sizeTip,
            fileList,
            beforeUpload,
            validFile,
            getSize,
            removeFile,
            uploadSuccess,
            uploadFail,
            overLimit,
            afterRead,
            onOversize,
            handleRemove,
            handlePictureCardPreview,
            handleDownload,
            download,
            _value
        }
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-upload-list__item) {
  transition: none;
}

.file-item {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>